<template>
  <div class="ai-chatbot">
    <el-drawer
        v-model="isChatOpen"
        title="AI 学习助手"
        direction="btt"
        :size="drawerHeight"
        :with-header="true"
        custom-class="chat-drawer"
        :resizable="false"
        :min-size="200"
        @closed="userInput = ''"
    >
      <template #header="{ close, titleId, titleClass }">
        <div
            class="drawer-handle"
            @mousedown="handleMouseDown"
        ></div>
        <h4 :id="titleId" :class="titleClass">AI 学习助手</h4>
      </template>

      <div class="chat-container">
        <div class="messages-container" ref="messagesContainerRef">
          <div
              v-for="(msg, index) in messages"
              :key="index"
              :class="['message-row', msg.role]"
          >
            <el-avatar :icon="msg.role === 'user' ? UserFilled : ChatDotRound" class="avatar"/>
            <div class="message-content">
              <div
                  class="markdown-body"
                  v-html="formatMessage(msg.content)"
              ></div>
            </div>
          </div>

          <div v-if="isLoading" class="message-row assistant">
            <el-avatar :icon="ChatDotRound" class="avatar"/>
            <div class="message-content">
              <div class="loading-dots">
                <span></span><span></span><span></span>
              </div>
            </div>
          </div>
        </div>

        <div class="input-area-wrapper">
          <div class="input-container">
            <el-input
                v-model="userInput"
                type="textarea"
                :autosize="{ minRows: 1, maxRows: 5 }"
                placeholder="向AI助手提问..."
                @keydown.enter.prevent="handleEnter"
                :disabled="isLoading"
                class="input-box"
            />
            <el-button
                @click="sendMessage"
                :loading="isLoading"
                :disabled="!userInput.trim()"
                class="send-button"
                circle
            >
              <el-icon><Promotion /></el-icon>
            </el-button>
          </div>
        </div>
      </div>
    </el-drawer>

    <el-button class="chat-toggle-btn" @click="isChatOpen = true" circle>
      <el-icon><ChatDotRound /></el-icon>
    </el-button>
  </div>
</template>

<script setup>
import { ref, nextTick, watch, onUnmounted } from 'vue';
import MarkdownIt from 'markdown-it';
import { myRequest } from '@/utils/request';
import { ElDrawer, ElAvatar, ElInput, ElButton, ElIcon } from 'element-plus';
import { Promotion, ChatDotRound, UserFilled } from '@element-plus/icons-vue';

const md = new MarkdownIt({
  html: true,
  breaks: true,
  linkify: true,
  typographer: true,
});

md.renderer.rules.table_open = function() {
  return '<div class="table-wrapper"><table class="markdown-table">\n';
};

md.renderer.rules.table_close = function() {
  return '</table></div>\n';
};

const isChatOpen = ref(false);
const userInput = ref('');
const messages = ref([
  { role: 'assistant', content: '你好！我是您的学习助手，有什么可以帮助您？' }
]);
const isLoading = ref(false);
const messagesContainerRef = ref(null);

const drawerHeight = ref('80vh');
const isDragging = ref(false);
const startY = ref(0);
const startHeight = ref(0);

const sendMessage = () => {
  if (!userInput.value.trim() || isLoading.value) return;
  const userMessage = userInput.value;
  messages.value.push({ role: 'user', content: userMessage });
  userInput.value = '';
  isLoading.value = true;
  const assistantMessageIndex = messages.value.length;
  messages.value.push({ role: 'assistant', content: '' });
  let accumulatedContent = '';

  myRequest.streamRequest({
    url: 'api/ai/chat-stream',
    data: { prompt: userMessage },
    onMessage: (data) => {
      accumulatedContent += data;
      if (messages.value[assistantMessageIndex]) {
        messages.value[assistantMessageIndex].content = accumulatedContent;
      }
    },
    onDone: () => { isLoading.value = false; },
    onError: (error) => {
      if (messages.value[assistantMessageIndex]) {
        messages.value[assistantMessageIndex].content = '抱歉，服务暂时遇到问题，请稍后再试。';
      }
      isLoading.value = false;
    }
  });
};

const handleEnter = (e) => {
  if (e.shiftKey) return;
  e.preventDefault();
  sendMessage();
};

const formatMessage = (content) => {
  if (!content) return '';

  let processedContent = content;

  const codeBlockRegex = /```(?:\w*\n)?([\s\S]+?)\n```/;
  processedContent = processedContent.replace(codeBlockRegex, (match, innerContent) => {
    return innerContent.trim();
  });

  return md.render(processedContent);
};

const handleMouseDown = (e) => {
  e.preventDefault();
  isDragging.value = true;
  startY.value = e.clientY;
  const currentHeight = parseFloat(drawerHeight.value);
  startHeight.value = drawerHeight.value.includes('vh')
      ? (currentHeight / 100) * window.innerHeight
      : currentHeight;
  document.addEventListener('mousemove', handleMouseMove);
  document.addEventListener('mouseup', handleMouseUp);
  document.body.style.userSelect = 'none';
};

const handleMouseMove = (e) => {
  if (!isDragging.value) return;
  const deltaY = e.clientY - startY.value;
  let newHeight = startHeight.value - deltaY;
  const maxHeight = window.innerHeight * 0.95;
  const minHeight = 200;
  newHeight = Math.max(minHeight, Math.min(maxHeight, newHeight));
  drawerHeight.value = `${newHeight}px`;
};

const handleMouseUp = () => {
  if (!isDragging.value) return;
  isDragging.value = false;
  document.removeEventListener('mousemove', handleMouseMove);
  document.removeEventListener('mouseup', handleMouseUp);
  document.body.style.userSelect = '';
};

onUnmounted(() => {
  if (isDragging.value) {
    document.removeEventListener('mousemove', handleMouseMove);
    document.removeEventListener('mouseup', handleMouseUp);
  }
});

watch(messages, () => {
  nextTick(() => {
    const container = messagesContainerRef.value;
    if (container) {
      container.scrollTop = container.scrollHeight;
    }
  });
}, { deep: true });
</script>

<style>
/* Unscoped styles - Re-verified for syntax correctness */
.chat-drawer .el-drawer__header {
  margin-bottom: 0;
  padding: 12px 20px;
  border-bottom: 1px solid #e0e0e0;
  position: relative;
  cursor: n-resize;
}
.chat-drawer .el-drawer__body {
  padding: 0;
  background-color: #ffffff;
  display: flex;
  flex-direction: column;
}
.chat-drawer .markdown-body .table-wrapper {
  overflow-x: auto;
  margin: 15px 0;
}
.chat-drawer .markdown-body .markdown-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #dfe2e5;
  font-size: 14px;
  display: table;
}
.chat-drawer .markdown-body .markdown-table th,
.chat-drawer .markdown-body .markdown-table td {
  border: 1px solid #dfe2e5;
  padding: 8px 12px;
  text-align: left;
  vertical-align: top;
}
.chat-drawer .markdown-body .markdown-table th {
  font-weight: 600;
  background-color: #f6f8fa;
}
.chat-drawer .markdown-body .markdown-table tr:nth-child(2n) {
  background-color: #f6f8fa;
}
</style>

<style scoped>
/* Scoped styles - Re-verified for syntax correctness */
.ai-chatbot {
  position: fixed;
  bottom: 30px;
  right: 30px;
  z-index: 2000;
}
.chat-toggle-btn {
  width: 56px;
  height: 56px;
  font-size: 24px;
  color: #1677FF;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
  background-color: #fff;
  border: 1px solid #eee;
}
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.messages-container {
  flex-grow: 1;
  overflow-y: auto;
  padding: 20px;
}
.message-row {
  display: flex;
  margin-bottom: 20px;
  max-width: 90%;
  align-items: flex-start;
}
.message-row.user {
  margin-left: auto;
  flex-direction: row-reverse;
}
.avatar {
  flex-shrink: 0;
  margin-top: 4px;
}
.message-row.user .avatar {
  margin-left: 12px;
}
.message-row.assistant .avatar {
  margin-right: 12px;
}
.message-content {
  padding: 10px 15px;
  border-radius: 18px;
  font-size: 15px;
  line-height: 1.6;
  word-break: break-word;
  overflow-x: auto;
  white-space: pre-line;
}
.message-row.user .message-content {
  background-color: #e3f2fd;
  border-bottom-right-radius: 4px;
}
.message-row.assistant .message-content {
  background-color: #f1f3f4;
  border-bottom-left-radius: 4px;
}
.markdown-body :deep(p) { margin: 0 0 10px 0; }
.markdown-body :deep(p):last-child { margin-bottom: 0; }
.markdown-body :deep(pre) {
  background-color: #282c34;
  color: #abb2bf;
  padding: 1rem;
  border-radius: 8px;
  white-space: pre-wrap;
  word-wrap: break-word;
  overflow-x: auto;
}
.markdown-body :deep(code) {
  font-family: 'Courier New', Courier, monospace;
  background-color: rgba(0,0,0,0.05);
  padding: 2px 4px;
  border-radius: 4px;
}
.input-area-wrapper {
  padding: 10px 20px 20px 20px;
  background-color: #fff;
  border-top: 1px solid #e0e0e0;
}
.input-container {
  display: flex;
  align-items: flex-end;
  gap: 10px;
  padding: 8px 8px 8px 20px;
  background-color: #f1f3f4;
  border-radius: 28px;
}
.input-box :deep(.el-textarea__inner) {
  background-color: transparent;
  box-shadow: none;
  padding: 6px 0;
  resize: none;
  border: none;
}
.send-button {
  width: 40px;
  height: 40px;
  font-size: 18px;
  background-color: transparent;
  color: #5f6368;
  border: none;
  box-shadow: none;
}
.drawer-handle {
  position: absolute;
  top: 5px;
  left: 50%;
  transform: translateX(-50%);
  width: 40px;
  height: 4px;
  background-color: #dcdfe6;
  border-radius: 2px;
  cursor: n-resize;
}
.loading-dots { display: flex; align-items: center; height: 24px; }
.loading-dots span {
  width: 8px;
  height: 8px;
  margin: 0 2px;
  background-color: #999;
  border-radius: 50%;
  animation: bounce 1.4s infinite ease-in-out both;
}
.loading-dots span:nth-child(1) { animation-delay: -0.32s; }
.loading-dots span:nth-child(2) { animation-delay: -0.16s; }
@keyframes bounce {
  0%, 80%, 100% { transform: scale(0); }
  40% { transform: scale(1.0); }
}
</style>